package com.yupi.springbootinit.controller;

import cn.hutool.core.io.FileUtil;
import com.yupi.springbootinit.bizmq.BiMessageProducer;
import com.yupi.springbootinit.common.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.yupi.springbootinit.annotation.AuthCheck;
import com.yupi.springbootinit.constant.CommonConstant;
import com.yupi.springbootinit.constant.FileConstant;
import com.yupi.springbootinit.constant.UserConstant;
import com.yupi.springbootinit.exception.BusinessException;
import com.yupi.springbootinit.exception.ThrowUtils;
import com.yupi.springbootinit.manager.AiManager;
import com.yupi.springbootinit.manager.RedisLimiterManager;
import com.yupi.springbootinit.model.dto.chart.*;
import com.yupi.springbootinit.model.dto.file.UploadFileRequest;
import com.yupi.springbootinit.model.dto.reverse.ServerLoadInfo;
import com.yupi.springbootinit.model.entity.Chart;
import com.yupi.springbootinit.model.entity.User;
import com.yupi.springbootinit.model.enums.FileUploadBizEnum;
import com.yupi.springbootinit.model.enums.ScoreChangeEnum;
import com.yupi.springbootinit.model.vo.BiResponse;
import com.yupi.springbootinit.service.ChartService;
import com.yupi.springbootinit.service.UserScoreService;
import com.yupi.springbootinit.service.UserService;
import com.yupi.springbootinit.utils.ExcelUtils;
import com.yupi.springbootinit.utils.ServerMetricsUtil;
import com.yupi.springbootinit.utils.SqlUtils;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 图表接口
 *
 */
@RestController
@RequestMapping("/chart")
@Slf4j
public class ChartController {

    @Resource
    private ChartService chartService;

    @Resource
    private UserService userService;

    @Resource
    private UserScoreService userScoreService;

    @Resource
    private AiManager aiManager;

    @Resource
    private RedisLimiterManager redisLimiterManager;

    @Resource
    // 自动注入一个线程池实例
    private ThreadPoolExecutor threadPoolExecutor;

    @Resource
    private BiMessageProducer biMessageProducer;


    // region 增删改查

    /**
     * 创建
     *
     * @param chartAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addChart(@RequestBody ChartAddRequest chartAddRequest, HttpServletRequest request) {
        if (chartAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartAddRequest, chart);
        User loginUser = userService.getLoginUser(request);
        chart.setUserId(loginUser.getId());
        boolean result = chartService.save(chart);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newChartId = chart.getId();
        return ResultUtils.success(newChartId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteChart(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldChart.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        System.out.println("正在删除图表");
        // 删除分表
        chartService.deleteTable(id);
        // 删除chart表数据
        boolean b = chartService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param chartUpdateRequest
     * @return
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateChart(@RequestBody ChartUpdateRequest chartUpdateRequest, HttpServletRequest request) {
        if (chartUpdateRequest == null || chartUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = chartUpdateRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);

        User loginUser = userService.getLoginUser(request);
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 仅本人或管理员可编辑
        if (!oldChart.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartUpdateRequest, chart);
        boolean result = chartService.updateById(chart);
        return ResultUtils.success(result);
    }

    /**
     * 根据图表id获取图表详细信息
     * @param id 图表id
     * @param request
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<Chart> getChartByChartId(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        Chart chart = chartService.getById(id);
        if (chart == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 仅本人或管理员可编辑
        if (!chart.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        String tableData = chartService.getTableData(id);
        chart.setChartData(tableData);
        return ResultUtils.success(chart);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<Chart> getChartById(long id, HttpServletRequest request) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = chartService.getById(id);
        if (chart == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(chart);
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param chartQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page")
    public BaseResponse<Page<Chart>> listChartByPage(@RequestBody ChartQueryRequest chartQueryRequest,
            HttpServletRequest request) {
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Chart> chartPage = chartService.page(new Page<>(current, size),
                getQueryWrapper(chartQueryRequest));
        return ResultUtils.success(chartPage);
    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param chartQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page")
    public BaseResponse<Page<Chart>> listMyChartByPage(@RequestBody ChartQueryRequest chartQueryRequest,
            HttpServletRequest request) {
        if (chartQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        chartQueryRequest.setUserId(loginUser.getId());
        long current = chartQueryRequest.getCurrent();
        long size = chartQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        Page<Chart> chartPage = chartService.page(new Page<>(current, size),
                getQueryWrapper(chartQueryRequest));
        return ResultUtils.success(chartPage);
    }

    // endregion

    /**
     * 编辑（用户）
     *
     * @param chartEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editChart(@RequestBody ChartEditRequest chartEditRequest, HttpServletRequest request) {
        if (chartEditRequest == null || chartEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Chart chart = new Chart();
        BeanUtils.copyProperties(chartEditRequest, chart);
        User loginUser = userService.getLoginUser(request);
        long id = chartEditRequest.getId();
        // 判断是否存在
        Chart oldChart = chartService.getById(id);
        ThrowUtils.throwIf(oldChart == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldChart.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean result = chartService.updateById(chart);
        return ResultUtils.success(result);
    }


    /**
     * 获取查询包装类
     *
     * @param chartQueryRequest
     * @return
     */
    private QueryWrapper<Chart> getQueryWrapper(ChartQueryRequest chartQueryRequest) {
        QueryWrapper<Chart> queryWrapper = new QueryWrapper<>();
        if (chartQueryRequest == null) {
            return queryWrapper;
        }
        Long id = chartQueryRequest.getId();
        String name = chartQueryRequest.getName();
        String goal = chartQueryRequest.getGoal();
        String chartType=  chartQueryRequest.getChartType();
        Long userId = chartQueryRequest.getUserId();
        String sortField = chartQueryRequest.getSortField();
        String sortOrder = chartQueryRequest.getSortOrder();

        queryWrapper.eq(id != null && id > 0,"id",id);
        queryWrapper.like(StringUtils.isNotBlank(name),"name",name);
        queryWrapper.eq(StringUtils.isNotBlank(goal),"goal",goal);
        queryWrapper.eq(StringUtils.isNotBlank(chartType),"chartType",chartType);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId),"userId",userId);
        queryWrapper.eq("isDelete", false);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    /**
     * 智能分析（同步）
     *
     * @param multipartFile
     * @param genChartByAiRequest
     * @param request
     * @return
     */
    @PostMapping("/gen")
    public BaseResponse<BiResponse> genChartByAi(@RequestPart("file") MultipartFile multipartFile,
                                                 GenChartByAiRequest genChartByAiRequest, HttpServletRequest request) {
        String name = genChartByAiRequest.getName();
        String goal = genChartByAiRequest.getGoal();
        String chartType = genChartByAiRequest.getChartType();
        //校验
        ThrowUtils.throwIf(StringUtils.isBlank(goal),ErrorCode.PARAMS_ERROR,"目标为空");
        ThrowUtils.throwIf(StringUtils.isNotBlank(name)&&name.length()>100,ErrorCode.PARAMS_ERROR,"名称过长");
        // 校验文件
        long size = multipartFile.getSize();    // 获取文件大小
        String originalFilename = multipartFile.getOriginalFilename();  // 获取文件原始名
        // 校验文件大小
        final long ONE_MB = 1024 * 1024L;
        ThrowUtils.throwIf(size > ONE_MB, ErrorCode.SYSTEM_ERROR, "文件大小不能超过1MB");
        // 校验文件后缀
        String suffix = FileUtil.getSuffix(originalFilename);
        final List<String> validFileSuffixList = (Arrays.asList("xlsx", "xls"));
        ThrowUtils.throwIf(!validFileSuffixList.contains(suffix), ErrorCode.SYSTEM_ERROR, "非法文件格式");

        User loginUser = userService.getLoginUser(request);
        // 限流判断，每个用户一个限流器
        // redisLimiterManager.doRateLimit("genChartByAi_" + String.valueOf(loginUser.getId()));
        redisLimiterManager.doRateLimit(String.valueOf(loginUser.getId()));

        long biModelId = CommonConstant.BI_MODEL_ID;


        //用户输入
        StringBuilder userInput = new StringBuilder();
        userInput.append("分析需求：").append("\n");

        /**
         * 拼接分析目标
         */
        String userGoal = goal;
        if (StringUtils.isNotBlank(chartType)){
            userGoal += "，请使用" + chartType;
        }
        userInput.append(userGoal).append("\n");
        userInput.append("原始数据：").append("\n");
        //压缩后的数据（转换为csv格式）
        String csvData = ExcelUtils.excelToCsv(multipartFile);
        userInput.append(csvData).append("\n");

        String result = aiManager.doChat(biModelId, userInput.toString());
        // String result = "【【【【【sh【【【【【ide";
        log.info("AI 生成的语句：\n{}", result);
        String[] splits = result.split("【【【【【");
        if (splits.length != 3) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "AI 生成错误");
        }

        // 第一段是空，所以从第二段开始取
        String genChart = splits[1].trim();
        String genResult = splits[2].trim();
        // 插入到数据库
        Chart chart = new Chart();
        chart.setName(name);
        chart.setGoal(goal);
        // chart.setChartData(csvData);
        chart.setChartType(chartType);
        chart.setGenChart(genChart);
        chart.setGenResult(genResult);
        chart.setUserId(loginUser.getId());
        chart.setStatus(FileConstant.SUCCEED);
        boolean saveResult = chartService.save(chart);
        ThrowUtils.throwIf(!saveResult, ErrorCode.SYSTEM_ERROR, "图表保存失败");
        // 将用户上传文件数据分表创建并存入一个新表
        chartService.setChartData(csvData, chart.getId());

        BiResponse biResponse = new BiResponse();
        biResponse.setGenChart(genChart);
        biResponse.setGenResult(genResult);
        biResponse.setChartId(chart.getId());
        return ResultUtils.success(biResponse);

    }

    /**
     * 智能分析（异步）
     *
     * @param multipartFile
     * @param genChartByAiRequest
     * @param request
     * @return
     */
    @PostMapping("/gen/async")
    public BaseResponse<BiResponse> genChartByAiAsync(@RequestPart("file") MultipartFile multipartFile,
                                             GenChartByAiRequest genChartByAiRequest, HttpServletRequest request) {
        String name = genChartByAiRequest.getName();
        String goal = genChartByAiRequest.getGoal();
        String chartType = genChartByAiRequest.getChartType();
        //校验
        ThrowUtils.throwIf(StringUtils.isBlank(goal),ErrorCode.PARAMS_ERROR,"目标为空");
        ThrowUtils.throwIf(StringUtils.isNotBlank(name)&&name.length()>100,ErrorCode.PARAMS_ERROR,"名称过长");
        // 校验文件
        ExcelUtils.checkExcelFile(multipartFile);

        User loginUser = userService.getLoginUser(request);
        // 限流判断，每个用户一个限流器
        // redisLimiterManager.doRateLimit("genChartByAi_" + String.valueOf(loginUser.getId()));
        redisLimiterManager.doRateLimit(String.valueOf(loginUser.getId()));

        long biModelId = CommonConstant.BI_MODEL_ID;


        //用户输入
        StringBuilder userInput = new StringBuilder();
        userInput.append("分析需求：").append("\n");

        /**
         * 拼接分析目标
         */
        String userGoal = goal;
        if (StringUtils.isNotBlank(chartType)){
            userGoal += "，请使用" + chartType;
        }
        userInput.append(userGoal).append("\n");
        userInput.append("原始数据：").append("\n");
        //压缩后的数据（转换为csv格式）
        String csvData = ExcelUtils.excelToCsv(multipartFile);
        userInput.append(csvData).append("\n");

        // 插入到数据库
        Chart chart = new Chart();
        chart.setName(name);
        chart.setGoal(goal);
        // chart.setChartData(csvData);
        chart.setChartType(chartType);
        chart.setStatus(FileConstant.WAIT);
        chart.setUserId(loginUser.getId());
        boolean saveResult = chartService.save(chart);
        ThrowUtils.throwIf(!saveResult, ErrorCode.SYSTEM_ERROR, "图表保存失败");
        // 将用户上传文件数据分表创建并存入一个新表
        chartService.setChartData(csvData, chart.getId());


        CompletableFuture.runAsync(() -> {
            //先修改图表任务状念为”执行中”。等执行成功后，修收为”已完成”、若执行中失败：状态修收为“执行失败”，记录任务失败信息
            Chart updateChart = new Chart();
            updateChart.setId(chart.getId());
            updateChart.setStatus(FileConstant.RUNNING);
            boolean b = chartService.updateById(updateChart);   // 修改数据库状态为执行中
            if (!b) {
                handleChartUpdateError(chart.getId(),"图表状态更改失败");
                return;
            }
            // 调用 AI
            try {
                String result = aiManager.doChat(biModelId, userInput.toString());
                // String result = "【【【【【sh【【【【【ide";
                log.info("AI 生成的语句：\n{}", result);
                String[] splits = result.split("【【【【【");
                if (splits.length != 3) {
                    handleChartUpdateError(chart.getId(),"AI 生成错误");
                    return;
                }

                // 第一段是空，所以从第二段开始取
                String genChart = splits[1].trim();
                String genResult = splits[2].trim();

                updateChart.setStatus(FileConstant.SUCCEED);
                updateChart.setGenChart(genChart);
                updateChart.setGenResult(genResult);
                boolean b1 = chartService.updateById(updateChart);// 修改数据库状态为执行完成
                if (!b1) {
                    handleChartUpdateError(chart.getId(),"图表状态更改失败");
                    return;
                }
            } catch (Exception exception) {
                exception.printStackTrace();
            }
        }, threadPoolExecutor);

        BiResponse biResponse = new BiResponse();
        biResponse.setChartId(chart.getId());
        return ResultUtils.success(biResponse);
    }

    /**
     * 智能分析（异步消息队列）
     * 访问 http://localhost:15672，默认用户名密码都是 guest(文档有说明)
     * @param multipartFile
     * @param genChartByAiRequest
     * @param request
     * @return
     */
    @PostMapping("/gen/async/mq")
    public BaseResponse<BiResponse> genChartByAiAsyncMq(@RequestPart("file") MultipartFile multipartFile,
                                                      GenChartByAiRequest genChartByAiRequest, HttpServletRequest request) {
        String name = genChartByAiRequest.getName();
        String goal = genChartByAiRequest.getGoal();
        String chartType = genChartByAiRequest.getChartType();
        //校验
        ThrowUtils.throwIf(StringUtils.isBlank(goal),ErrorCode.PARAMS_ERROR,"目标为空");
        ThrowUtils.throwIf(StringUtils.isNotBlank(name)&&name.length()>100,ErrorCode.PARAMS_ERROR,"名称过长");
        // 校验文件
        ExcelUtils.checkExcelFile(multipartFile);
        // 获取用户信息
        User loginUser = userService.getLoginUser(request);
        // 限流判断，每个用户一个限流器
        // redisLimiterManager.doRateLimit("genChartByAi_" + String.valueOf(loginUser.getId()));
        redisLimiterManager.doRateLimit(String.valueOf(loginUser.getId()));
        //
        // long biModelId = CommonConstant.BI_MODEL_ID;
        //
        //
        // //用户输入
        // StringBuilder userInput = new StringBuilder();
        // userInput.append("分析需求：").append("\n");
        //
        // /**
        //  * 拼接分析目标
        //  */
        // // String userGoal = goal;
        // if (StringUtils.isNotBlank(chartType)){
        //     goal += "，请使用" + chartType;
        // }
        // userInput.append(goal).append("\n");
        // userInput.append("原始数据：").append("\n");
        //压缩后的数据（转换为csv格式）
        String csvData = ExcelUtils.excelToCsv(multipartFile);
        // userInput.append(csvData).append("\n");

        // 插入到数据库
        Chart chart = new Chart();
        chart.setName(name);
        chart.setGoal(goal);
        // chart.setChartData(csvData);
        chart.setChartType(chartType);
        chart.setStatus(FileConstant.WAIT);
        chart.setUserId(loginUser.getId());
        boolean saveResult = chartService.save(chart);
        ThrowUtils.throwIf(!saveResult, ErrorCode.SYSTEM_ERROR, "图表保存失败");

        Long newChartId = chart.getId();
        // 将用户上传文件数据分表创建并存入一个新表
        chartService.setChartData(csvData, newChartId);
        // 将消息放入消息队列中
        biMessageProducer.sendMessage(String.valueOf(newChartId));

        BiResponse biResponse = new BiResponse();
        biResponse.setChartId(newChartId);
        return ResultUtils.success(biResponse);
    }

    /**
     * 智能图表(异步) : 消息队列
     * @TODO 反向压力
     *
     * @param multipartFile 数据文件
     * @param chartRequest  图要求
     * @return {@link BaseResponse}<{@link BiResponse}>
     */
    @PostMapping("/gen/async/reverse")
    // @Operation(summary = "通过ai生成图表")
    public BaseResponse<BiResponse> genChartByAiReverse(@RequestPart("file") MultipartFile multipartFile,
                                                 GenChartByAiRequest chartRequest, HttpServletRequest request) {
        // 1.save chat(Not Generated)
        // 取出数据
        String name = chartRequest.getName();
        String goal = chartRequest.getGoal();
        String chartType = chartRequest.getChartType();
        // 校验
        ThrowUtils.throwIf(StringUtils.isBlank(goal), ErrorCode.PARAMS_ERROR, "目标为空!");
        ThrowUtils.throwIf(StringUtils.isNotBlank(name) && name.length() > 100, ErrorCode.PARAMS_ERROR, "名称过长!");
        // 获取用户信息
        User user = userService.getLoginUser(request);
        Long userId = user.getId();
        // redisLimiterManager.doRateLimit(RedisConstant.GEN_CHART_LIMIT_KEY + user.getId());
        redisLimiterManager.doRateLimit(String.valueOf(userId));
        // 校验文件
        ExcelUtils.checkExcelFile(multipartFile);
        // 读取文件信息
        String csvData = ExcelUtils.excelToCsv(multipartFile);
        ThrowUtils.throwIf(csvData.length() > 1000, ErrorCode.SYSTEM_ERROR, "原始信息过长!");
        // 插入数据到数据库
        Chart chartEntity = new Chart();
        chartEntity.setUserId(userId);
        chartEntity.setName(name);
        chartEntity.setGoal(goal);
        chartEntity.setGenType(UserConstant.YUAI_TYPE);
        chartEntity.setStatus(FileConstant.WAIT);
        chartEntity.setChartType(chartType);
        boolean save = chartService.save(chartEntity);
        ThrowUtils.throwIf(!save, ErrorCode.SYSTEM_ERROR, "保存图表失败!");
        chartEntity.setChartData(csvData);
        // 将用户上传文件数据分表创建并存入一个新表
        chartService.setChartData(csvData, chartEntity.getId());

        // 在这里选择执行的策略
        //1. 获取当前执行状态
        ServerLoadInfo info = ServerMetricsUtil.getLoadInfo();
        //2. 执行图表生成
        // 校验用户积分是否足够并扣除对应的积分
        Boolean checkAndDeduct = userScoreService.checkAndDeduct(userId, ScoreChangeEnum.GEN_CHART_DEDUCT.getValue());
        ThrowUtils.throwIf(!checkAndDeduct, ErrorCode.INSUFFICIENT_POINTS_ERROR, "积分不足!");
        try{
            BiResponse biResponse = chartService.genChart(chartEntity,info);
            if (StringUtils.isNotBlank(biResponse.getGenChart())) {
                return ResultUtils.success(biResponse);
            }
            return ResultUtils.success(biResponse);
        }catch (BusinessException businessException){
            if(businessException.getCode() == ErrorCode.TOO_MANY_REQUEST.getCode()){
                // 如果执行的是拒绝策略 , 那么退回扣除的积分
                // userScoreService.sendCompensate(userId, ScoreChangeEnum.GEN_CHART_DEDUCT.getValue());
            }
            throw businessException;
        }
    }

    /**
     * 图表生成失败后重试
     * @param chartId 图表id
     * @return
     */
    @GetMapping("/retry")
    public BaseResponse<BiResponse> retryChart(Long chartId){
        Chart chart = chartService.getById(chartId);
        String status = chart.getStatus();
        Long userId = chart.getUserId();
        String genType = chart.getGenType();
        Byte isDelete = chart.getIsDelete();
        ThrowUtils.throwIf(isDelete != 0, ErrorCode.NOT_FOUND_ERROR, "图表已删除!");
        ThrowUtils.throwIf(!StringUtils.isNotBlank(status) && (!status.equals("failed") || !status.equals("wait")), ErrorCode.TOO_MANY_REQUEST, "操作繁忙，请等待图表生成!");
        // 限流
        redisLimiterManager.doRateLimit(String.valueOf(userId));
        // 查询数据库是否存在此表
        boolean isTable = chartService.queryTableNumber(chartId);
        ThrowUtils.throwIf(isTable, ErrorCode.NOT_FOUND_ERROR, "数据缺失无法重新生成!");
        // 获取原始表格的数据
        String tableData = chartService.getTableData(chartId);
        ThrowUtils.throwIf(tableData.length() > 1000, ErrorCode.SYSTEM_ERROR, "原始信息过长!");

        Chart chartEntity = new Chart();
        chartEntity.setId(chartId);
        chartEntity.setUserId(userId);
        chartEntity.setName(chart.getName());
        chartEntity.setGoal(chart.getGoal());
        chartEntity.setStatus(FileConstant.WAIT);
        chartEntity.setChartType(chart.getChartType());
        chartEntity.setChartData(tableData);

        // 在这里选择执行的策略
        if (genType.equals(UserConstant.WENXIN_TYPE)){
            // 将消息放入消息队列中
            log.info("将消息放入消息队列中。");
            biMessageProducer.sendMessageByWenxin(String.valueOf(chartId));

            BiResponse biResponse = new BiResponse();
            biResponse.setChartId(chartId);
            return ResultUtils.success(biResponse);
        }
        //1. 获取当前执行状态
        ServerLoadInfo info = ServerMetricsUtil.getLoadInfo();
        //2. 执行图表生成
        try{
            BiResponse biResponse = chartService.genChart(chartEntity,info);
            if (StringUtils.isNotBlank(biResponse.getGenChart())) {
                return ResultUtils.success(biResponse);
            }
            return ResultUtils.success(biResponse);
        }catch (BusinessException businessException){
            throw businessException;
        }
    }

    private void handleChartUpdateError(long chartId,String execMessage) {
        Chart updateChartResult = new Chart();
        updateChartResult.setId(chartId);
        updateChartResult.setStatus(FileConstant.FAILED);
        updateChartResult.setExecMessage("execMessage1");
        boolean updateResult = chartService.updateById(updateChartResult);
        if (!updateResult) {
            log.error("更新图表为失败状态 失败" + chartId + "," + execMessage);
        }
    }


}
